import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * @Author YuanYuan
 * @Date 2022/7/16
 * @Time 14:37
 */


public class Solution {

    public int[] smallestK(int[] arr, int k) {
        int[] node = new int[k];
        if(k == 0) {
            return node;
        }
        //建一个大小为4的大根堆
        if(arr.length<=k) {
            return arr;
        }
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(k, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2-o1;
            }
        });
        for (int i = 0; i < k; i++) {
            priorityQueue.offer(arr[i]);
        }
        int i = k;
        while(i<arr.length) {
            int top = priorityQueue.peek();
            if(arr[i]< top) {
                priorityQueue.poll();
                priorityQueue.offer(arr[i]);
            }
            i++;
        }
        for (int j = 0; j < k; j++) {
            node[j] = priorityQueue.poll();
        }
        return node;
    }
}
